<!-- 调度日志 -->
<script lang="ts" setup>
import { reactive, ref, computed } from 'vue'
import type { IDbAction, IDbSearchConfig, IDbSelect, IDbTable, ITagData } from '@/types/global'
import * as taskApi from '@/api/task'
import { ENUM_BTN_AUTH_TASK } from '@/config/btn'
import { DISPATH_SUCCESS_CODE, EXECUTE_SUCCESS_CODE, TASK_LOG_STATUS_LIST, ENUM_TASK_LOG_STATUS } from './config/config'
import LogClear from './comps/LogClear.vue'
import MarkDialog from './comps/MarkDialog.vue'
import { useRoute } from 'vue-router'

const logClearRef = ref<InstanceType<typeof LogClear>>()
const markDialogRef = ref<InstanceType<typeof MarkDialog>>()
// 执行器列表
const executorList = ref<IDbSelect[]>([])
// 任务列表
const taskList = ref<IDbSelect[]>([])
// 搜索栏配置
const searchConfig = computed<IDbSearchConfig[]>(() => {
  const configList: IDbSearchConfig[] = [
    { label: '状态', prop: 'logStatus', type: 'select', list: TASK_LOG_STATUS_LIST, options: { clearable: false } },
    {
      label: '执行器',
      prop: 'jobGroup',
      type: 'select',
      list: executorList.value,
      change: executorChangeEvt,
      options: { clearable: false }
    },
    { label: '任务', prop: 'jobId', type: 'select', list: taskList.value },
    {
      label: '时间',
      prop: 'timeRangeList',
      type: 'date',
      width: '420px',
      options: { type: 'datetimerange', startPlaceholder: '开始时间', endPlaceholder: '结束时间' }
    }
  ]
  return configList
})

// 表格数据
const tableData = reactive<IDbTable>({
  columns: [
    { label: '任务ID', prop: 'jobId', width: '100px' },
    { label: '调度时间', prop: 'triggerTime', minWidth: '180px' },
    {
      label: '调度结果',
      prop: 'handleCode',
      width: '120px',
      type: 'tag',
      tagFunc: (scoped) => {
        const label = scoped.row.triggerCode == DISPATH_SUCCESS_CODE ? '成功' : '失败'
        const type = scoped.row.triggerCode == DISPATH_SUCCESS_CODE ? 'success' : 'danger'
        const params: ITagData = { label, type }
        return params
      }
    },
    { label: '调度备注', prop: 'triggerMsg', type: 'slot', width: '120px' },
    { label: '执行时间', prop: 'handleTime', minWidth: '180px' },
    {
      label: '执行结果',
      prop: 'handleCode',
      width: '120px',
      type: 'tag',
      tagFunc: (scoped) => {
        const label = scoped.row.handleCode == EXECUTE_SUCCESS_CODE ? '成功' : '失败'
        const type = scoped.row.handleCode == EXECUTE_SUCCESS_CODE ? 'success' : 'danger'
        const params: ITagData = { label, type }
        return params
      }
    },
    { label: '执行备注', prop: 'handleMsg', type: 'slot', width: '120px' },
    { label: '操作', prop: 'handle', fixed: 'right', type: 'slot', width: '120px' }
  ],
  data: [],
  total: 0,
  search: {
    pageNum: 1,
    pageSize: 20,
    logStatus: ENUM_TASK_LOG_STATUS['全部'],
    jobGroup: '',
    jobId: '',
    timeRangeList: [] as any[]
  }
})

initData()

/**
 * 点击清理
 */
function clearClick() {
  logClearRef.value?.init()
}
/**
 * 点击调度备注
 */
function dispatchRemarkClick(triggerMsg: any) {
  markDialogRef.value?.init('调度备注', triggerMsg || '无')
}
/**
 * 点击执行备注
 */
function executeRemarkClick(handleMsg: any) {
  markDialogRef.value?.init('执行备注', handleMsg || '无')
}
/**
 * 点击执行日志
 */
function logClick(scoped: any) {
  taskApi
    .getTaskLogInfo({
      logId: scoped.row.id,
      triggerTime: Date.parse(scoped.row.triggerTime),
      executorAddress: scoped.row.executorAddress,
      fromLineNum: 1
    })
    .then((res) => {
      if (res.success) {
        markDialogRef.value?.init('执行日志', res.data?.data?.logContent || '无')
      }
    })
}
/**
 * 获取表格数据
 */
function getDataList() {
  const params: any = { ...tableData.search, filterTime: tableData.search!.timeRangeList.join(' - ') }
  delete params.timeRangeList
  taskApi.getTaskLogByPage(params).then((res) => {
    if (res.success) {
      tableData.total = res.data?.total || 0
      tableData.data = res.data?.rows || []
    }
  })
}
/**
 * 设置表格按钮
 */
function setBtnList(scoped: any) {
  const list: IDbAction[] = [
    { label: '执行日志', type: 'primary', show: scoped.row.triggerCode == DISPATH_SUCCESS_CODE, onClick: () => logClick(scoped) }
  ]
  return list
}
/**
 * 执行器选择回调
 */
function executorChangeEvt(initJobId: boolean = true) {
  if (initJobId === true) {
    tableData.search!.jobId = ''
  }
  taskApi.getTaskByExecutor(tableData.search!.jobGroup).then((res) => {
    if (res.success) {
      const rows = res.data?.data || []
      taskList.value = rows.map((item: any) => {
        return { label: item.jobDesc, value: item.id }
      })
    }
  })
}
/**
 * 初始化
 */
function initData() {
  const query = useRoute().query
  const queryParams = {
    jobId: query.jobId ? parseInt(query.jobId as string) : null,
    jobGroup: query.jobGroup ? parseInt(query.jobGroup as string) : null
  }
  taskApi.getTaskExecutorkByPage({ pageNum: 1, pageSize: 99 }).then((res) => {
    if (res.success) {
      const executeRows = res.data?.rows || []
      executorList.value = executeRows.map((item: any) => {
        return { label: item.appname, value: item.id }
      })
      // 如果从其他页面传递了参数则用传递的参数，否则取列表第一个
      tableData.search!.jobGroup = queryParams.jobGroup ?? (executorList.value[0]?.value || '')
      tableData.search!.jobId = queryParams.jobId ?? ''
      executorChangeEvt(false)
      getDataList()
    }
  })
}
</script>

<template>
  <dui-page :search-config="searchConfig" :search-data="tableData.search" @search="getDataList">
    <template #btn>
      <db-auth-btn :auth="ENUM_BTN_AUTH_TASK['调度日志:清理']" icon-type="del" type="primary" @click="clearClick">
        清理
      </db-auth-btn>
    </template>
    <template #default>
      <dui-table
        :data="tableData.data"
        :columns="tableData.columns"
        :total="tableData.total"
        :search="tableData.search"
        @search="getDataList"
      >
        <template #triggerMsgSlot="scoped">
          <el-button v-if="scoped.row.triggerMsg" type="primary" link @click="dispatchRemarkClick(scoped.row.triggerMsg)">
            查看
          </el-button>
          <span v-else>-</span>
        </template>
        <template #handleMsgSlot="scoped">
          <el-button v-if="scoped.row.handleMsg" type="primary" link @click="executeRemarkClick(scoped.row.handleMsg)">
            查看
          </el-button>
          <span v-else>-</span>
        </template>
        <template #handleSlot="scoped">
          <dui-action :list="setBtnList(scoped)" />
        </template>
      </dui-table>
      <!-- 弹窗 -->
      <LogClear ref="logClearRef" @refresh="getDataList" />
      <MarkDialog ref="markDialogRef" />
    </template>
  </dui-page>
</template>
